package yanglib.application.metadata.server;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with IntelliJ IDEA.
 * User: user
 * Date: 9/6/14
 * Time: 8:42 PM
 * To change this template use File | Settings | File Templates.
 */
public class MemStorage {
    private ConcurrentHashMap<ByteBuffer, byte[]> map = new ConcurrentHashMap<ByteBuffer, byte[]>();
    private final String logPath;
    private RandomAccessFile currentLog = null;
    private int currentLogID = 0;
    private static final long maxLogSize = 64L * 1024L * 1024L;

    public MemStorage(String logPath) {
        this.logPath = logPath;
    }

    private void createNewLogIfNecessary() throws IOException {

        if (currentLog == null || currentLog.length() > maxLogSize) {
            String logFileName = logPath + File.separator + "log_" + currentLogID;
            if (currentLog != null)
                currentLog.close();
            currentLog = new RandomAccessFile(logFileName, "rw");
            currentLogID++;
        }


    }

    public void put(byte[] key, byte[] value) throws IOException {
        createNewLogIfNecessary();
        currentLog.writeInt(key.length);
        currentLog.write(key);
        currentLog.write(value.length);
        currentLog.write(value);
        //map.put(ByteBuffer.wrap(key), value);
    }

    public byte[] get(byte[] key) throws IOException{
        return map.get(ByteBuffer.wrap(key));
    }
}
